package com.ecommerce.user.config;

import com.ecommerce.user.security.JwtAuthenticationFilter;
import com.ecommerce.user.security.GatewayUserInfoFilter;
import com.ecommerce.user.security.AdminPermissionFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.client.RestTemplate;

/**
 * 安全配置类
 */
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {

    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;
    
    @Autowired
    private GatewayUserInfoFilter gatewayUserInfoFilter;
    
    @Autowired
    private AdminPermissionFilter adminPermissionFilter;

    /**
     * 密码编码器
     * @return BCryptPasswordEncoder
     */
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * RestTemplate Bean
     * @return RestTemplate
     */
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    /**
     * 安全过滤器链
     * @param http HttpSecurity
     * @return SecurityFilterChain
     * @throws Exception 异常
     */
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            // 禁用CSRF
            .csrf(csrf -> csrf.disable())
            // 禁用Session
            .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            // 授权请求
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/users/register", "/api/users/login").permitAll()
            .requestMatchers("/api/users/sync").permitAll()  // 允许认证服务同步用户数据
            .requestMatchers("/api/users/sync-password/**").permitAll()  // 允许认证服务同步用户密码
            .requestMatchers("/api/users/list").permitAll()  // 公开的用户列表接口
            .requestMatchers("/api/users/**").permitAll()  // 允许所有用户相关接口（包括获取用户信息）
            .requestMatchers("/api/users/password/**").authenticated()  // 密码修改接口需要认证
            .requestMatchers("/api/admin/**").hasRole("ADMIN")  // 管理员接口需要ADMIN角色
            .requestMatchers("/api/test/**").permitAll()  // 测试接口
            .requestMatchers("/actuator/**").permitAll()
                .anyRequest().authenticated()
            );
        
        // 显式添加JWT过滤器到过滤器链中
        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        http.addFilterAfter(gatewayUserInfoFilter, JwtAuthenticationFilter.class);
        http.addFilterAfter(adminPermissionFilter, GatewayUserInfoFilter.class); // 添加管理员权限过滤器
        
        return http.build();
    }
}